<template>
  <VDialog @close="handleClose" title="新增" @save="save" :loading="loading">
    <template #content>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="字段名称" prop="name">
          <VGroup class="w-[100%]">
            <el-input
              v-model="formData.name"
              placeholder="字段名称"
              class="w-[90%]"
            />
            <el-switch
              v-model="formData.status"
              inline-prompt
              active-text="启用"
              inactive-text="禁用"
              class="ml-[16px]"
              :active-value="1"
              :inactive-value="0"
            />
          </VGroup>
        </el-form-item>
        <el-form-item label="字段值">
          <el-input
            v-model="formData.value"
            placeholder="字段值"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="所属模块">
          <el-cascader
            :options="options?.menusList || []"
            v-model="formData.menu_id"
            :props="propsCascader"
            clearable
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
    </template>
  </VDialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { propsCascader } from "../../data.js";
import api from "../../api/index.js";
const props = defineProps({
  options: { type: Object, default: () => {} },
  id: { type: [Number, String], default: "" },
});
const { options } = toRefs(props);
watch(
  () => props.id,
  async (val) => {
    if (!val) return;
    const { data } = await api.fieldAttrdetail({ id: val });
    for (let key in formData) {
      formData[key] = data[key];
    }
  }
);
const formRef = ref();
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const loading = ref(false);
const rules = reactive({
  name: [{ required: true, message: "字段名称不能为空", trigger: "blur" }],
});
const formData = reactive({
  id: null,
  name: null,
  status: 0,
  value: null,
  menu_id: null,
});
const handleClose = async (refresh) => {
  for (let key in formData) {
    formData[key] = null;
  }
  formData.status = 0;
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
const save = async () => {
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true;
        const { code, message } = await (formData?.id
          ? api.fieldAttrUpdate
          : api.fieldAttrCreate)({ ...formData });
        if (code !== 200) return;
        ElMessage.success(message);
        handleClose(true);
      } catch (error) {
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>
